package com.lashou.chunshen.lashoutuangou.fragments;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lashou.chunshen.lashoutuangou.R;
import com.lashou.chunshen.lashoutuangou.adapter.HomeBannerAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.HomeShoppingGvAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.HomeShoppingUnderLoopAdvAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.HomeSpecialGvAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.MyViewPagerAdapter01;
import com.lashou.chunshen.lashoutuangou.adapter.TopLinePageAdapter;
import com.lashou.chunshen.lashoutuangou.bean.BaseBean;
import com.lashou.chunshen.lashoutuangou.bean.HomeBanner;
import com.lashou.chunshen.lashoutuangou.bean.HomeCategory;
import com.lashou.chunshen.lashoutuangou.bean.HotFilm;
import com.lashou.chunshen.lashoutuangou.core.BaseFragment;
import com.lashou.chunshen.lashoutuangou.nohttp.CallServer;
import com.lashou.chunshen.lashoutuangou.nohttp.HttpListner;
import com.lashou.chunshen.lashoutuangou.nohttp.helper.BeanJsonRequest;
import com.lashou.chunshen.lashoutuangou.tools.ConstantPool;
import com.lashou.chunshen.lashoutuangou.tools.L;
import com.lashou.chunshen.lashoutuangou.tools.PicassoUtils;
import com.lashou.chunshen.lashoutuangou.widget.GestateViewPager;
import com.lashou.chunshen.lashoutuangou.widget.GridViewWithHeaderAndFooter;
import com.lashou.chunshen.lashoutuangou.widget.MyGridView;
import com.lashou.chunshen.lashoutuangou.widget.banner.Banner;
import com.lashou.chunshen.lashoutuangou.widget.banner.BannerPagerAdapter;
import com.lashou.chunshen.lashoutuangou.widget.verticalviewpager.VerticalViewPager;
import com.lashou.chunshen.lashoutuangou.widget.verticalviewpager.transformer.DefaultTransformer;
import com.yolanda.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

import static com.lashou.chunshen.lashoutuangou.R.id.tv_ad_desc;
import static com.lashou.chunshen.lashoutuangou.R.id.tv_ad_title;

/**
 * Created by Administrator on 2016/9/2.
 */

public class HomeFragment extends BaseFragment implements AbsListView.OnScrollListener {
    @InjectView(R.id.psv_to_refresh)
    PullToRefreshListView pullToRefreshListView; //总框架
    @InjectView(R.id.top_bar)
    RelativeLayout titleBar; //titlebar
    Banner banner;
    GestateViewPager fenleiViewPager;
    LinearLayout pointLayout;
    VerticalViewPager topLine;
    MyGridView gv_shopping;
    int gdNum; //计算分类的总页数
    ImageView v_line;
    View h_line;
    TextView tv_ad_title1,tv_ad_desc1,tv_ad_title2,tv_ad_desc2,tv_ad_title3,tv_ad_desc3;
    ImageView iv_ad1,iv_ad2,iv_ad3,twelveIv;
    GridViewWithHeaderAndFooter gridviewithheard;

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        View headerView = View.inflate(getActivity(), R.layout.fragment_home_main, null);
        headerView.setLayoutParams(layoutParams);
        banner = (Banner) headerView.findViewById(R.id.banner);
        fenleiViewPager = (GestateViewPager) headerView.findViewById(R.id.vp_type);
        pointLayout = (LinearLayout) headerView.findViewById(R.id.iv_image);
        //TopLine
        topLine = (VerticalViewPager)headerView.findViewById(R.id.vp_headlines);
        //购物gv
        gv_shopping = (MyGridView)headerView.findViewById(R.id.gv_special);
        v_line = (ImageView)headerView.findViewById(R.id.v_line);
        h_line = (View)headerView.findViewById(R.id.h_line);
        //banner for 3
        tv_ad_title1 = (TextView) headerView.findViewById(R.id.first).findViewById(tv_ad_title);
        tv_ad_desc1 = (TextView) headerView.findViewById(R.id.first).findViewById(tv_ad_desc);
        iv_ad1 = (ImageView) headerView.findViewById(R.id.first).findViewById(R.id.iv_ad);

        tv_ad_title2 = (TextView) headerView.findViewById(R.id.second).findViewById(tv_ad_title);
        tv_ad_desc2 = (TextView) headerView.findViewById(R.id.second).findViewById(tv_ad_desc);
        iv_ad2 = (ImageView) headerView.findViewById(R.id.second).findViewById(R.id.iv_ad);

        tv_ad_title3 = (TextView) headerView.findViewById(R.id.threer).findViewById(tv_ad_title);
        tv_ad_desc3 = (TextView) headerView.findViewById(R.id.threer).findViewById(tv_ad_desc);
        iv_ad3 = (ImageView) headerView.findViewById(R.id.threer).findViewById(R.id.iv_ad);

        //轮播广告下面的banner
        gridviewithheard = (GridViewWithHeaderAndFooter) headerView.findViewById(R.id.gridviewithheard);
        twelveIv = (ImageView)headerView.findViewById(R.id.twelveIv);

        pullToRefreshListView.getRefreshableView().addHeaderView(headerView);
        pullToRefreshListView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, strs));
        pullToRefreshListView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, strs));
        pullToRefreshListView.setOnScrollListener(this);
        initData(); //创建所有接口数据

    }
    /**创建分类圆点标签**/
    private void initPoint() {
        for(int i=0;i<gdNum;i++){
            pointLayout.setVisibility(View.VISIBLE);
            ImageView iv = new ImageView(getHoldingActivity());
            iv.setImageResource(R.drawable.guide_third);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(8,8);
            lp.setMargins(5,0,0,0);
            iv.setLayoutParams(lp);
            pointLayout.addView(iv);
        }
    }

    private void initData() {
        //banner
        BeanJsonRequest<HomeBanner> bannerBeanJsonRequest = new BeanJsonRequest<HomeBanner>(ConstantPool.BANNER,HomeBanner.class);
        CallServer.getInstance().add(getActivity(),0,bannerBeanJsonRequest,httpListner,false,true);
        //首页分类
        BeanJsonRequest<HomeCategory> homeCategoryJsonRequest = new BeanJsonRequest<HomeCategory>(ConstantPool.HOMECATEGORY,HomeCategory.class);
        CallServer.getInstance().add(getActivity(),1,homeCategoryJsonRequest,httpListner,false,true);


    }
    /**获取网络数据**/
    HttpListner httpListner = new HttpListner<BaseBean>() {
        @Override
        public void onSucceed(int what, Response<BaseBean> response) {
            switch (what) {
                case 0:
                    HomeBanner baseBean = (HomeBanner) response.get();
                    initBanner(baseBean);
                    initPoint();//创建分类圆点标签
                    initTopLine(baseBean);//创建拉手头条
                    initGvShopping(baseBean);//创建gridview的购物
                    initShoppingForThreeBanner(baseBean);//创建gridview的购物
                    initShoppingUnderLoopAdv(baseBean);//创建轮播广告下面的数据

                    break;
                case 1:
                    HomeCategory homecategory = (HomeCategory) response.get();
                    initHomeCategory(homecategory);
                    break;
                case 2:
                    HotFilm hotFile = (HotFilm) response.get();
                    break;
            }

        }
        @Override
        public void onFailed(int what, Response<BaseBean> response) {

        }
    };
    /**创建轮播广告下面的数据**/
    private void initShoppingUnderLoopAdv(HomeBanner baseBean) {
        List<HomeBanner.ResultsBean.BottomFourBannerBean> bean = baseBean.getResults().getBottom_four_banner();
        HomeBanner.ResultsBean.BottomBigBannerBean bottom_big_banner = baseBean.getResults().getBottom_big_banner();
        List<HomeBanner.ResultsBean.BottomTwoBannerBean> bottom_two_banner = baseBean.getResults().getBottom_two_banner();
        if(null != bean){
            gridviewithheard.setAdapter(new HomeShoppingUnderLoopAdvAdapter(getHoldingActivity(),baseBean));
        }
        if(null != bottom_big_banner){
            PicassoUtils.loadImageViewHolder(mActivity,bottom_big_banner.img_big,R.drawable.home_adver_640,twelveIv);
        }
        //增加gridview的头部
        if(null != bottom_two_banner){
            View view = View.inflate(getHoldingActivity(), R.layout.griditem_home_shoppingunderloopadv_heard, null);
        //    gridviewithheard.addHeaderView(view);
        }
    }

    /**创建gridview的购物**/
    private void initShoppingForThreeBanner(HomeBanner baseBean) {
        List<HomeBanner.ResultsBean.CenterThreeBannerBean> bean = baseBean.getResults().getCenter_three_banner();
        if(null != bean){
            for (int i=0;i<bean.size();i++){
                switch (i){
                    case 0 :
                        tv_ad_title1.setText(bean.get(i).getMain_title());
                        tv_ad_desc1.setText(bean.get(i).getSub_title());
                        PicassoUtils.loadImageViewHolder(mActivity,bean.get(i).getImg_mid(),R.drawable.home_class_default_icon,iv_ad1);
                        break;
                    case 1 :
                        tv_ad_title2.setText(bean.get(i).getMain_title());
                        tv_ad_desc2.setText(bean.get(i).getSub_title());
                        PicassoUtils.loadImageViewHolder(mActivity,bean.get(i).getImg_mid(),R.drawable.home_class_default_icon,iv_ad2);
                        break;
                    case 2 :
                        tv_ad_title3.setText(bean.get(i).getMain_title());
                        tv_ad_desc3.setText(bean.get(i).getSub_title());
                        PicassoUtils.loadImageViewHolder(mActivity,bean.get(i).getImg_mid(),R.drawable.home_class_default_icon,iv_ad3);
                        break;
                }

            }
        }
    }

    /**创建gridview的购物**/
    private void initGvShopping(HomeBanner baseBean) {
        gv_shopping.setAdapter(new HomeShoppingGvAdapter(getHoldingActivity(),baseBean));
        v_line.setVisibility(View.VISIBLE);
        h_line.setVisibility(View.VISIBLE);
    }

    /**创建拉手头条**/
    private void initTopLine(HomeBanner homeBanner) {
        topLine.setAdapter(new TopLinePageAdapter<HomeBanner>(getHoldingActivity(),homeBanner));
        topLine.setPageTransformer(false, new DefaultTransformer());
    }

    /**首页分类**/
    private void initHomeCategory(HomeCategory homecategory) {
         //计算首页分类的size
        int totalType = homecategory.getResults().size();
        gdNum = totalType%8==0?totalType/8:totalType/8+1;
        int startNum = 0;
        int endNum = 8;
        //保存每个gv的数据
        List<GridView> datas = new ArrayList<GridView>();
        for(int i=0;i<gdNum;i++){
            MyGridView gv = new MyGridView(getHoldingActivity());
            GridView.LayoutParams lParams = new GridView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,
                    AbsListView.LayoutParams.WRAP_CONTENT);
            gv.setLayoutParams(lParams);
            gv.setNumColumns(4);
            gv.setHorizontalSpacing(0);
            gv.setVerticalSpacing(0);
            gv.setAdapter(new HomeSpecialGvAdapter(getHoldingActivity(),homecategory.getResults().subList(startNum,endNum)));
            startNum = startNum+8;
            endNum = endNum*gdNum;
            datas.add(gv);
        }
        fenleiViewPager.setOffscreenPageLimit(3);
        fenleiViewPager.setAdapter(new MyViewPagerAdapter01(datas));
    }

    /**创建banner**/
    private void initBanner(HomeBanner homeBanner) {
        /**
         * 关于这里的设置参数问题,是需要这样使用的
         * 在设置了小圆点之后才能设置适配器
         * 因为只有在适配器里才会根据一共多少条数据来适配
         * 最后需要调用开始轮播
         * 个人建议在onPause()/onDestroy()方法中来停止 -- stopAutoPlay()
         */
        HomeBannerAdapter bannerAdapter = new HomeBannerAdapter(getHoldingActivity(),homeBanner);
        bannerAdapter.setSize(homeBanner.getResults().getHeader_banner().size());

        banner.setDot(R.drawable.banner_white_radius, R.drawable.banner_red_radius).
                setDotGravity(Banner.CENTER).
                setAdapter(bannerAdapter).
                setOnItemClickListener(new BannerPagerAdapter.onItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        Toast.makeText(getHoldingActivity(),  position, Toast.LENGTH_SHORT).show();
                    }
                }).
                startAutoPlay();
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_a;
    }
    /**构建listview的假数据**/
    private static final String[] strs = new String[] {
        "first", "second", "third", "fourth", "fifth"
    };

    /**监听listview的滑动**/
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
         //获取titlebar的高度
        int height = titleBar.getHeight();
        float top = view.getChildAt(0).getY();
        L.i("@@@@@@@@@@",height+"---"+top+"firstVisibleItem"+firstVisibleItem);
    }
}
